# --! coding=utf-8 !--
# coding=utf-8
# Copyright (c) [2025] [2578713815@qq.com]
# [AHPU_EQM] is licensed under Mulan PSL v2.
"""
核心程序\n
author: <2578713815@qq.com>\n
"""
import threading
import time
from CONFIG import settings
from Utils import dbUtils, timeUtils
from threading import Thread
from APP import servo, log_manager


RED = settings.RED
GREEN = settings.GREEN
YELLOW = settings.YELLOW
BLUE = settings.BLUE
GRAY = settings.GRAY
RESET = settings.RESET


def data_update_loop(event: threading.Event, save_path: str = settings.DATA_PATH):
	"""
	用于在每日6:00和18:00获取电量信息的子线程函数
	:param save_path: 保存电量信息的文件路径
	:param event: 启动事件
	:return:
	"""
	print(GREEN + ">>> Local Data Servo Start." + RESET)
	while True:
		print(GREEN + ">>> Waiting For Local Data Updating..." + RESET)
		event.wait()
		build_id_info = dbUtils.get_json_info(settings.BUILDINGS_PATH)
		users_data = dbUtils.get_users_data(settings.USERS_DATA_PATH)
		info_to_request = dbUtils.get_need_to_request_info(users_data)
		data_to_save = [["build", "room", "electric"]]
		for info in info_to_request:
			build_name = info[0]  # 楼栋名
			room_id = info[1]  # 房间号
			build_code = build_id_info[build_name]
			electric = dbUtils.request_data(room_id, build_code, build_name)
			if electric:
				save_list = [f"{build_name}", f"{room_id}", f"{electric[0]}"]
				print(GREEN + f">>> Save info: {save_list}" + RESET)
				data_to_save.append(save_list)
			else:
				continue
		dbUtils.save_data_to_csv(data_list=data_to_save, save_path=save_path)
		event.clear()


def servo_loop(event: threading.Event):
	"""
	用户服务线程函数
	:param event: 服务启动事件
	:return:
	"""
	time.sleep(5)  # 启动时等待5秒，避免潜在的io冲突
	print(GREEN+">>> User Servo Start."+RESET)
	while True:
		print(GREEN + ">>> Waiting For Servo Time(/30m)..." + RESET)
		event.wait()
		print(">>> Checking Msg To Send...")
		user_data = dbUtils.get_users_data(settings.USERS_DATA_PATH)
		user_num = len(user_data)
		user_mode_data = dbUtils.get_user_data_with_mode(user_data)
		for mode_data, index in zip(user_mode_data[::-1], list(range(len(user_mode_data)))[::-1]):
			if len(mode_data) > 0:
				print(BLUE + f">>> Mode <{index}>{RESET}:", mode_data)
				for i in mode_data:
					statu_code = servo.servo_funcs[index](i, user_num)  # 执行服务函数，返回状态码
					if statu_code is not None:
						print(settings.STATU_CODE[statu_code], i)
					time.sleep(settings.SEND_TIME_INTERVAL)
			else:
				print(GRAY+f">>> No users in mode<{index}>..."+RESET)
		event.clear()


def main():
	"""
	主线程
	:return:
	"""
	update_event = threading.Event()
	servo_event = threading.Event()
	update_event.clear()

	data_update_thread = Thread(target=data_update_loop, args=(update_event, settings.DATA_PATH))  # 信息更新线程
	update_controller_thread = Thread(target=timeUtils.update_controller, args=(update_event,))  # 信息更新管控线程
	servo_thread = Thread(target=servo_loop, args=(servo_event,))  # 主服务线程
	servo_start_thread = Thread(target=timeUtils.servo_start_controller, args=(servo_event,))  # 主服务管控线程
	user_statu_cleaner = Thread(target=timeUtils.clean_user_status_controller)  # 用户信息状态重置线程
	log_manager_thread = Thread(target=log_manager.log_cleaner)  # 日志清理线程

	data_update_thread.start()
	update_controller_thread.start()
	servo_start_thread.start()
	servo_thread.start()
	user_statu_cleaner.start()
	log_manager_thread.start()

	data_update_thread.join()
	update_controller_thread.join()
	servo_thread.join()
	log_manager_thread.join()
	servo_start_thread.join()
	user_statu_cleaner.join()
